package com.zg.datapush.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.dao.system.SysDatasource;
import com.zg.common.core.dao.system.SysDatasourceDao;
import com.zg.common.dds.DataSourceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 数据源测试服务
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DatasourceTestService {

    private final SysDatasourceDao sysDatasourceDao;
    private final DataSourceUtil dataSourceUtil;
    private final JdbcTemplate jdbcTemplate;

    /**
     * 测试数据源连接
     */
    public boolean testConnection(String datasourceCode) {
        try {
            SysDatasource datasource = sysDatasourceDao.getOne(
                new LambdaQueryWrapper<SysDatasource>()
                    .eq(SysDatasource::getCode, datasourceCode)
            );

            if (datasource == null) {
                log.error("数据源不存在: {}", datasourceCode);
                return false;
            }

            // 使用DataSourceUtil切换到指定数据源
            dataSourceUtil.change(datasourceCode);

            try {
                // 执行简单查询测试连接
                jdbcTemplate.queryForObject("SELECT 1", Integer.class);
                return true;
            } finally {
                // 清理数据源切换
                dataSourceUtil.clear();
            }

        } catch (Exception e) {
            log.error("数据源连接测试失败: {}", datasourceCode, e);
            return false;
        }
    }


}
